package com.ohy.tencent.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ohy.tencent.config.Contan;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@RestController
@RequestMapping("youku")
@Slf4j
public class YouKuVideoController {

    String tvClassJson = "";
    String mvClassJson = "";

    @GetMapping(value = "getClass")
    public String getMVClass(@RequestParam(value = "type", defaultValue = "1") Integer type) {
        String key = type.equals(1) ? "video:youku:mvClass" : "video:youku:tvClass";
        String classJson = getClassJson(type.equals(1) ? "mv" : "tv");
        return classJson;
    }

    @GetMapping(value = "getVideo")
    public String getVideo(@RequestParam(value = "p", required = false, defaultValue = "1") int p,
                           @RequestParam(value = "u", required = false, defaultValue = "") String u,
                           @RequestParam(value = "s", required = false, defaultValue = "") String s,
                           @RequestParam(value = "d", required = false, defaultValue = "") String d,
                           @RequestParam(value = "a", required = false, defaultValue = "") String a,
                           @RequestParam(value = "g", required = false, defaultValue = "") String g,
                           @RequestParam(value = "r", required = false, defaultValue = "") String r,
                           @RequestParam(value = "pt", required = false, defaultValue = "") String pt,
                           @RequestParam(value = "type", required = false, defaultValue = "mv") String type) {

        String url = "https://list.youku.com/category/page?c=" + (type.equals("mv") ? "96" : "97") +
                "&u=" + u +
                "&s=" + s +
                "&d=&" + d +
                "a=" + a +
                "&g=" + g +
                "&r=" + r +
                "&pt=" + pt +
                "&type=show" +
                "&p=" + p;
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse execute = get.execute();
        return execute.body();
    }

    @GetMapping(value = "getTVInfo")
    public String getTVInfo(@RequestParam(value = "url") String url) {
        if (url.contains("https://www.soku.com/m/t/show")) {
            String s = HttpUtil.get(url);
            url = s.substring(s.indexOf("0) {window.location=\"") + "0) {window.location=\"".length(), s.length());
            url = url.substring(0, url.indexOf("\""));
        }
        url += "==.html";
        if (!url.contains("http")) url = "https:" + url;
        String s = HttpUtil.get(url);
        Document parse = Jsoup.parse(s);
        String t = parse.getElementsByClass("title").get(0).text();
        int page = parse.getElementsByClass("video-status").size() > 0 ? Integer.valueOf(Pattern.compile("[^0-9]").matcher(parse.getElementsByClass("video-status").get(0).getElementsByTag("span").size() >= 3 ? parse.getElementsByClass("video-status").get(0).getElementsByTag("span").get(2).text() : parse.getElementsByClass("video-status").get(0).text()).replaceAll("").trim()) : 0;
        if (page == 0) page++;
        else page = (int) (Math.ceil(page / 50.0));
        s = s.substring(s.indexOf("showid: '") + "showid: '".length());
        s = s.substring(0, s.indexOf("'"));
        JSONObject res = new JSONObject();
        List<JSONObject> list = new LinkedList<>();
        for (int i = 1; i <= page; i++) {
            url = "https://v.youku.com/page/playlist?showid=" + s + "&isSimple=false&page=" + i;
            HttpRequest get = HttpUtil.createGet(url);
            HttpResponse execute = get.execute();
            Document document = Jsoup.parse(JSONObject.parseObject(execute.body()).getString("html"));
            Elements item = document.getElementsByClass("item");
            for (Element data : item) {
                if (data.toString().contains("预")) continue;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", data.attr("seq"));
                jsonObject.put("title", data.attr("title"));
                jsonObject.put("href", data.getElementsByTag("a").get(0).attr("href"));
                jsonObject.put("img", data.getElementsByTag("img").get(0).attr("_src"));
                list.add(jsonObject);
            }
        }
        res.put("data", list);
        res.put("title", t);
        return res.toJSONString();
    }

    @GetMapping(value = "getSearch")
    public String getSearch(@RequestParam(value = "word") String word) throws UnsupportedEncodingException {
        String url = "https://tip.soku.com/search_tip_1?query=" + URLEncoder.encode(word, "UTF-8");
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse execute = get.execute();
        return execute.body();
    }


    @GetMapping(value = "getSearchRes")
    public String getSearchRes(@RequestParam(value = "word") String word) throws UnsupportedEncodingException {
        String url = "https://www.soku.com/m/y/video?q=" + URLEncoder.encode(word, "UTF-8");
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse execute = get.execute();
        String res = execute.body();
        Document parse = Jsoup.parse(res);
        Elements elements = parse.getElementsByClass("yk_card");
        List<JSONObject> list = new ArrayList<>();
        for (Element element : elements) {
            try {
                if (!element.getElementsByClass("v_pos").toString().contains("优酷")) continue;
                if (element.getElementsByClass("v_desc").toString().contains("电影")) {

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("title", element.getElementsByClass("name").get(0).text());
                    jsonObject.put("pic", element.getElementsByTag("img").get(0).attr("src"));
                    jsonObject.put("url", element.getElementsByClass("btn_blue").get(0).attr("href"));
                    jsonObject.put("type", "mv");
                    list.add(jsonObject);
                } else if (element.getElementsByClass("v_pe").toString().contains("选集")) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("title", element.getElementsByClass("name").get(0).text());
                    jsonObject.put("pic", element.getElementsByTag("img").get(0).attr("src"));
                    jsonObject.put("url", element.getElementsByClass("btn_blue").get(0).attr("href"));
                    jsonObject.put("type", "tv");
                    list.add(jsonObject);
                }

            } catch (Exception e) {
                log.error("优酷解析搜索异常", e);
            }
        }
//        elements = parse.getElementsByClass("yk_col4");
//        for (Element element : elements) {
//            try {
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("title", element.getElementsByTag("a").get(0).attr("_log_title"));
//                jsonObject.put("pic", element.getElementsByTag("img").get(0).attr("src"));
//                url = "https://www.soku.com" + element.getElementsByTag("a").get(0).attr("href");
//                jsonObject.put("url", url);
//                jsonObject.put("type", "tv");
//                list.add(jsonObject);
//            } catch (Exception e) {
//                log.error("优酷解析搜索异常", e);
//            }
//        }
        return list.toString();
    }

    private String getClassJson(String type) {
        String cookie = " UM_distinctid=16e545e968d395-082a5b85619854-34564a75-1fa400-16e545e968eb50; cna=uak4Fu/A13cCAXd7hTNsXX8V; __ysuid=15733735157193E4; juid=01dpa5tn9fb1b; __aryft=1575716682; P_gck=NA%7CkYkVD4dejdgEYN1DWyoO8w%3D%3D%7CNA%7C1575716829308; P_pck_rm=Az1NkqAS83dab1cd9bae0bZB%2B4vbocoRHQQc%2FRxZyyUR0zh799eqmmavJIGa7tbCyCR2fJiIn248JPSMHuekzbJDllMqlBhbzpyoSYxeb4Y1I1AeISFAUWty9QwskmppNuqO5CumE0frRkd63JQBu3rd9Qxjun218gR%2BZA%3D%3D%5FV2; __ayft=1576739597328; __aysid=1576739597328IcZ; __ayscnt=1; _m_h5_tk=36fdad4f1fd87eefbb5751ef3c595c93_1576744636828; _m_h5_tk_enc=667ebfe62ccc3fc19df982b3380d8ba5; _m_h5_c=483ad2ce2fb039573c4306675fbaa690_1576747879213%3Bdb711c45f00ce40a18ffb89868dcfec8; ykss=1723fb5d499643e5624e019d; P_sck=fUTFxSPXyO1NfNVr8lgrbEId7zJlGXC9oZz%2FccNHkP5ZZUzkIsPmkJmcKu53IYjCvBksbTO%2BT%2FjYC%2FbIASE7KOmfvkGN015hjbh7u9e78o7RlTKD15Rs103QdN8bYAiQavoCHFVpFb%2FvYTp3PRm1FA%3D%3D; CNZZDATA1277956656=1765345124-1575714733-https%253A%252F%252Fmovie.youku.com%252F%7C1576737239; ypvid=1576739648081Z4ACoW; yseid=1576739648082ex7ssm; ysestep=1; yseidcount=3; yseidtimeout=1576746848083; ycid=0; ystep=5; seid=01dseg3cil1d6c; referhost=; seidtimeout=1576741448086; P_ck_ctl=2B7EB6B853E462BE78388D050C2F1196; _zpdtk=e3b9f66773d7b1bda678861f9a0a847e5a7a5290; __arpvid=1576741159993PNWd2Z-1576741160098; __aypstp=35; __ayspstp=35; isg=BDY2XTQBd3rVIgMiFsKGKjWnkmz4_3r3scqr16AfdJm049Z9COdhoX4B-f8q0HKp";
        String tvUrl = "https://list.youku.com/category/show/c_96.html";
        String mvUrl = "https://list.youku.com/category/show/c_97.html";
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet httpGet = new HttpGet(type.equals("mv") ? tvUrl : mvUrl);
                httpGet.addHeader("cookie", cookie);
                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                if (!result.contains("window.__INITIAL_DATA__ =")) return type.equals("mv") ? mvClassJson : tvClassJson;
                result = result.substring(result.indexOf("window.__INITIAL_DATA__ =") + "window.__INITIAL_DATA__ =".length(), result.indexOf(";window._SSRERR_=false;"));
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (type.equals("mv"))
                    mvClassJson = jsonObject.getJSONObject("categoryFilter").getJSONObject("filter").toString();
                else
                    tvClassJson = jsonObject.getJSONObject("categoryFilter").getJSONObject("filter").toString();
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        }
        return type.equals("mv") ? mvClassJson : tvClassJson;
    }

}
